<template>
  <!-- 成员维护页 -->
  <div class="member-defend">
    <div class="deal-box">
      <div class="search-box">
        <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="68px" @submit.native.prevent>
          <el-form-item label="部门" >
            <treeselect v-model.trim="queryParams.deptCode" :options="deptOptions" :show-count="true" placeholder="请选择归属部门" style="width:200px;" size="small"/>
          </el-form-item>
          <el-form-item label="职级">
            <el-select v-model.trim="queryParams.dutyLevel" placeholder="请选择" size="small" style="width: 200px">
              <el-option
                v-for="item in typeOptions"
                :key="item.dictValue"
                :label="item.dictLabel"
                :value="item.dictValue"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="用户名">
            <el-input
              class="search-input"
              placeholder="请输入用户名"
              v-model.trim="queryParams.userName"
              clearable
              size="small"
              style="width:200px"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="用户编码">
            <el-input
              class="search-input"
              placeholder="请输入用户编码"
              v-model.trim="queryParams.userCode"
              clearable
              size="small"
              style="width:200px"
            >
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div class="deal-list">
      <el-button
        type="primary"
        size="mini"
        icon="el-icon-plus"
        @click="addMember"
        >新增</el-button
      >
      <el-button type="danger" icon="el-icon-delete" :disabled="multiple" @click="delMember" size="mini">删除</el-button>
    </div>  
    <el-table
      border
      :data="tableData"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange"
      v-loading="loading"
    >
      <el-table-column type="selection" width="55" fixed></el-table-column>
      <el-table-column prop="areaName" label="行政区划" :resizable="false"></el-table-column>
      <el-table-column prop="orgCode" label="组织机构" :resizable="false"></el-table-column>
      <el-table-column prop="deptName" label="部门" :resizable="false"></el-table-column>
      <el-table-column prop="dutyLevel" label="职务级别" :resizable="false"></el-table-column>
      <el-table-column prop="userName" label="用户" :resizable="false"></el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="pageIndex"
      :limit.sync="pageSize"
      @pagination="getList"
    />
    <!-- 新增用户弹窗 -->
    <el-dialog title="新增用户" :visible.sync="show" width="800px" :close-on-click-modal="false">
      <el-form ref="form" :model="form" label-width="80px" :inline="true">
        <el-form-item label="部门">
          <treeselect v-model.trim="form.deptCode" :options="deptOptions" :show-count="true" placeholder="请选择归属部门" style="width:200px"/>
        </el-form-item>
        <el-form-item label="职级">
          <el-select v-model.trim="form.dutyLevel" placeholder="请选择">
            <el-option
              v-for="item in typeOptions"
              :key="item.dictValue"
              :label="item.dictLabel"
              :value="item.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="handleUsers" style="margin-left:20px">查询</el-button>
        </el-form-item>
        <el-form-item label="用户名">
          <el-input
            class="search-input"
            placeholder="请输入用户名"
            v-model.trim="form.userName"
            clearable
            size="small"
            style="width:200px"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="用户编码">
          <el-input
            class="search-input"
            placeholder="请输入用户编码"
            v-model.trim="form.userCode"
            clearable
            size="small"
            style="width:200px"
          >
          </el-input>
        </el-form-item> 
      </el-form>
      <el-table
        border
        :data="usersData"
        tooltip-effect="dark"
        style="width: 100%"
        ref="tableUser"
        height="380"
        @selection-change="handleSelectionChangeUser"
      >
        <el-table-column type="selection" width="55" fixed :selectable='selectInit'></el-table-column>
        <el-table-column prop="areaName" label="行政区划" :resizable="false"></el-table-column>
        <el-table-column prop="orgCode" label="组织机构" :resizable="false"></el-table-column>
        <el-table-column prop="deptName" label="部门" :resizable="false"></el-table-column>
        <el-table-column prop="dutyLevel" label="职务级别" :resizable="false"></el-table-column>
        <el-table-column prop="userName" label="用户" :resizable="false"></el-table-column>
      </el-table>
      <div style="height:30px">
        <el-button type="primary" @click="saveUser" style="float:right;margin-top:10px">保存</el-button>
      </div>
      <pagination
        v-show="totalUser>0"
        :total="totalUser"
        :page.sync="pageIndexs"
        :limit.sync="pageSizes"
        @pagination="getUserList"
      />
      
    </el-dialog>
  </div>
</template>
<script>
import { getRoleUsers, delRoleUser, addRoleUser } from "@/api/system/role";
import { treeselect } from "@/api/system/dept";
import { checkDetails } from "@/api/system/user";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
  data(){
    return{
      //搜索条件
      queryParams: {
        roleCode: this.$route.query.roleCode,
        lx: "1"
      },
      // 非多个禁用
      multiple: true,
      typeOptions: [],//职级
      // 部门树选项
      deptOptions: [],
      tableHeight:0,  // table高度
      tableData:[],// 表格数据
      multipleSelection: [
        { id:'2', location: '渝北', jigou: '水利局', part: '行政', job: '主管', user:'张三，李四，王五' },
      ],  // 选中数据
      total: 0,  // 总共条数
      pageIndex: 1,
      pageSize: 20,
      ids:[],//选中要删除的id
      show:false, //新增用户弹窗显示
      form:{
        roleCode: this.$route.query.roleCode,
      },//新增用户搜索条件
      usersData:[],//新增用户列表数据
      totalUser:0,//新增用户列表总数
      pageIndexs:1,
      pageSizes:10,
      checkedId:[],//已添加的用户
      loading: true,
      userCodes:[],//批量新增用户
    }
  },
  components:{
    Treeselect
  },
  watch: {
    $route() {
      this.form.roleCode = this.$route.query.roleCode;
      this.queryParams.roleCode = this.$route.query.roleCode;
    }
  },
  activated() {
    this.getTreeselect();//部门
    this.checkDetail();//职级
    this.getList();//获取列表
  },
  methods:{
    /**
     * 获取列表
     */
    getList() {
      this.loading = true;
      let param = {
        parameter: this.queryParams,
        pageIndex: this.pageIndex,
        pageSize: this.pageSize
      }
      getRoleUsers(param).then(res => {
        if(res.status == 200){
          this.tableData = res.data.list;
          this.total = res.data.total;
        }else{
          this.tableData = [];
          this.total = 0;
        }
        this.loading = false;
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.initTree(response.data)
      });
    },
    // 部门树结构格式化
    initTree( tree ){
      tree.forEach(item=>{
        item.id = item.value;
        if( item.children && item.children.length > 0 ){
          this.initTree(item.children)
        }
      })
      this.deptOptions = tree;
    },
    /** 查询部门 */
    checkDetail() {
      checkDetails("DUTYLEVEL").then(response => {
        this.typeOptions = response.data
      });
    },
    /** 搜索 */
    handleQuery() {
      this.pageIndex = 1;
      this.getList()
    }, 
    /**
     * 多选
     */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userRoleId);
      this.multiple = !selection.length;
    },
    /**
     * 新增用户
     */
    addMember() {
      this.show = true;
      this.getUserList()
    },
    /**
     * 删除用户
     */
    delMember() {
      let userIds = this.ids;
      if( userIds.length !=0 ){
        userIds = userIds.join(',');
      }else {
        this.msgError("请选择要删除的用户");
        return
      }
      this.$confirm('确定是否删除此用户，删除后不可恢复?', '用户删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let param = {
          parameter: {
            userRoleIds: userIds
          }
        }
        return delRoleUser(param,this.$route.query.childCode);
      }).then((res) => {
        if(res.status == 200){
          this.getList();
          this.msgSuccess("删除成功");
        }else if(res.status == 101){
          this.msgError(res.errors[0].message);
        }
      })
    },
    /**
     * 新增用户搜索
     */
    handleUsers() {
      this.pageIndexs = 1;
      this.getUserList();
    },
    /**
     * 新增用户多选
     */
    handleSelectionChangeUser(selection) {
      this.userCodes = selection.map(item => item.userCode);
    },
    /**
     * 新增用户列表数据
     */
    getUserList() {
      let param = {
        parameter: this.form,
        pageIndex: this.pageIndexs,
        pageSize: this.pageSizes
      }
      getRoleUsers(param).then(res => {
        if(res.status == 200){
            this.usersData = res.data.list;
            this.totalUser = res.data.total;
            this.$nextTick(()=>{
              for(let key in this.usersData){
                if(this.usersData[key]['lx'] == "1") {
                  this.$refs.tableUser.toggleRowSelection(this.usersData[key],true)
                  this.checkedId.push(this.usersData[key]['userCode'])
                }
              }
            })
          }else if(res.status == 102){
            this.msgError(res.errors[0].message)
          }
 
        }
      );
    },
    //已选禁用，禁止再选择
    selectInit(row){
      if(row.lx=="1"){
        return false  //不可勾选
      }else{    
        return true  //可勾选
      }
    },
    /**
     * 新增用户保存
     */
    saveUser() {
      let userCodes = [];
      for(let key in this.userCodes) {
        if (this.checkedId.indexOf(this.userCodes[key]) == -1) {
          userCodes.push(this.userCodes[key])
        }
      }
      if( userCodes.length != 0 ){
        userCodes = userCodes.join(',');
      }else {
        this.msgWarning("请选择要新增的用户");
        return
      }
      let param = {
        parameter: {
          userCodes: userCodes,
          roleCode: this.$route.query.roleCode,
        }
      }
      addRoleUser(param,this.$route.query.childCode).then(res => {
        if(res.status == 200){
          this.msgSuccess("新增成功");
          this.getList();
        }else if(res.status == 101){
          this.msgError(res.errors[0].message);
        }
        this.show = false;
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.member-defend{
  padding: 20px;
  height: 100%;
  box-sizing: border-box;
  .deal-box {
    display: flex;
    align-items: center;
    justify-content: flex-start;
    margin-bottom: 20px;
    .select-box {
      width:300px;
    }
    .search-box {
      display: flex;
      align-items: center;
      .search-input {
        width: 260px;
        margin-right: 15px;
      }
    }
    
  }
  .deal-list {
      display: flex;
      align-items: center;
      margin-right: 20px;
      margin-bottom: 10px;
    }
  .btn-box{
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-top: 30px;
    .el-button{
      width: 80px;
      margin-left: 30px;
    }
  }
}
/deep/.el-dialog:not(.is-fullscreen) {
    margin-top: 4vh !important;
}
/deep/ .el-form-item--medium .el-form-item__content{
  line-height: 30px !important;
}
/deep/ .vue-treeselect__control{
  height: 30px !important;
}
</style>
